package cn.edu.baiyunu.myapplication.ui.screens.add.components

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.ArrowForward
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Divider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

/**
 * 自定义日期选择器
 */
@Composable
fun DatePicker(
    initialDate: Date = Date(),
    onDateSelected: (Date) -> Unit,
    onDismiss: () -> Unit
) {
    // 当前选择的日期
    var currentDate by remember { mutableStateOf(initialDate) }
    
    // 获取当前日历对象
    val calendar = Calendar.getInstance().apply {
        time = currentDate
    }
    
    val year = calendar.get(Calendar.YEAR)
    val month = calendar.get(Calendar.MONTH)
    val daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH)
    
    // 获取月份第一天是星期几
    val firstDayOfMonth = Calendar.getInstance().apply {
        set(year, month, 1)
    }.get(Calendar.DAY_OF_WEEK) - 1  // 0表示星期日
    
    // 创建日期网格数据
    val days = (1..daysInMonth).map { day ->
        DayItem(
            day = day,
            isSelected = day == calendar.get(Calendar.DAY_OF_MONTH)
        )
    }
    
    // 在日期前添加空白占位
    val allItems = List(firstDayOfMonth) { DayItem(day = -1, isSelected = false) } + days
    
    Dialog(onDismissRequest = onDismiss) {
        Surface(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            color = Color(0xBF333333),
            shape = RoundedCornerShape(16.dp)
        ) {
            Column(
                modifier = Modifier
                    .padding(16.dp)
            ) {
                // 月份显示和导航
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    IconButton(
                        onClick = {
                            val newCalendar = Calendar.getInstance().apply {
                                time = currentDate
                                add(Calendar.MONTH, -1)
                            }
                            currentDate = newCalendar.time
                        }
                    ) {
                        Icon(
                            imageVector = Icons.Default.ArrowBack, 
                            contentDescription = "上个月",
                            tint = Color.White
                        )
                    }
                    
                    Text(
                        text = SimpleDateFormat("yyyy年MM月", Locale.getDefault()).format(currentDate),
                        color = Color.White,
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Medium
                    )
                    
                    IconButton(
                        onClick = {
                            val newCalendar = Calendar.getInstance().apply {
                                time = currentDate
                                add(Calendar.MONTH, 1)
                            }
                            currentDate = newCalendar.time
                        }
                    ) {
                        Icon(
                            imageVector = Icons.Default.ArrowForward, 
                            contentDescription = "下个月",
                            tint = Color.White
                        )
                    }
                }
                
                Spacer(modifier = Modifier.height(16.dp))
                
                // 星期标题栏
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    val weekdays = listOf("日", "一", "二", "三", "四", "五", "六")
                    weekdays.forEach { day ->
                        Text(
                            text = day,
                            modifier = Modifier.weight(1f),
                            color = Color.White.copy(alpha = 0.7f),
                            textAlign = TextAlign.Center,
                            fontSize = 14.sp
                        )
                    }
                }
                
                Spacer(modifier = Modifier.height(8.dp))
                
                // 日期网格
                LazyVerticalGrid(
                    columns = GridCells.Fixed(7),
                    modifier = Modifier.height(200.dp)
                ) {
                    items(allItems) { item ->
                        DayCell(
                            item = item,
                            onDaySelected = { selectedDay ->
                                val newCalendar = Calendar.getInstance().apply {
                                    time = currentDate
                                    set(Calendar.DAY_OF_MONTH, selectedDay)
                                }
                                currentDate = newCalendar.time
                            }
                        )
                    }
                }
                
                Spacer(modifier = Modifier.height(16.dp))
                
                // 底部操作按钮
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    TextButton(
                        onClick = onDismiss
                    ) {
                        Text(
                            text = "取消",
                            color = Color.White.copy(alpha = 0.7f)
                        )
                    }
                    
                    Button(
                        onClick = {
                            onDateSelected(currentDate)
                            onDismiss()
                        },
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(0x4026DE81)
                        )
                    ) {
                        Text(
                            text = "确认",
                            color = Color.White
                        )
                    }
                }
            }
        }
    }
}

/**
 * 日期项数据类
 */
private data class DayItem(
    val day: Int,  // -1表示空白占位符
    val isSelected: Boolean
)

/**
 * 日期单元格
 */
@Composable
private fun DayCell(
    item: DayItem,
    onDaySelected: (Int) -> Unit
) {
    Box(
        modifier = Modifier
            .padding(4.dp)
            .size(32.dp)
            .clip(CircleShape)
            .background(
                if (item.isSelected) Color.White.copy(alpha = 0.25f) 
                else Color.Transparent
            )
            .then(
                if (item.day > 0) Modifier.clickable { onDaySelected(item.day) }
                else Modifier
            ),
        contentAlignment = Alignment.Center
    ) {
        if (item.day > 0) {
            Text(
                text = item.day.toString(),
                color = Color.White,
                fontSize = 14.sp,
                fontWeight = if (item.isSelected) FontWeight.Bold else FontWeight.Normal
            )
        }
    }
} 